import financeAuditService from '../financial-management/new-finance-audit/finance-audit.service';
import { messages, } from 'share/common';
import React from 'react';
import httpFetch from 'share/httpFetch';
import config from 'config';
import errorMessage from 'share/errorMessage';

export default {
  // 查验
  testInvoice(invoiceInfo, userOID, type, id, expenseReportOID, isFinancialOperateType, isInvoiceFromFinancialEntry) {
    let params = { invoiceInfo };
    userOID && (params.userOID = userOID);
    expenseReportOID && (params.expenseReportOID = expenseReportOID);
    let url = '';
    if (isInvoiceFromFinancialEntry) {
      url = '/api/receipt/finance/verify';
      params.entityId = id;
      params.entityType = type;
    } else {
      url = '/api/receipt/verify';
      params.entityType = type;
      params.finance = !!isFinancialOperateType;
    }
    return httpFetch.post(`${config.receiptUrl}${url}`, params)
      .catch(err => {
        errorMessage(err.response);
        throw err;
      });
  },
  //批注列表
  getAnnotateList(key, annotates = [], loginUser) {
    let list = annotates.filter(a => a.targetKey === key || a.key === key);
    list.map(item => item.disabled = item.createdBy !== loginUser.userOID);
    return list;
  },
  //获取批注信息
  async getAnnotate(currentInvoiceOID) {
    const res = await financeAuditService.getAnnotateByEntityOID(currentInvoiceOID, 'INVOICE');
    let annotates = res.data;
    annotates.map(item => {
      let target = item.target && JSON.parse(item.target);
      item.targetKey = target && target.type;
      item.key = target && target.key;
      if (target && ~['fieldOID', 'mileage', 'mileagePrice'].indexOf(target.type)) {
        //累计里程、补贴总额、里程明细
        if (!~['totalMileage', 'totalSubsidy', 'mileageDetail'].indexOf(target.key)) {
          item.targetKey = target.key;
        }
      }
      return item;
    });
    return annotates;
  },
  // 处理费用详情信息
  handleExpenseData({ currentExpense, currentExpenseType, expenseReport, showOCRFlag, options, profile, unitInfo }) {
    const {
      owner, expenseTypeName, expenseTypeIconURL, createdDate, manualAudit, invoiceOID, id,
      originalApprovedNonVat, originalApprovedVat, invoiceCurrencyCode, originalAmount, currencyCode, actualCurrencyRate,
      amount, companyCurrencyRate, expenseTypeSubsidyType, unitPrice, number, mileageAllowanceExpenseV2DTO, originalActualCurrencyRate,
      data = [], subsidyAmount, receiptList = [], withReceipt, invoiceInstead, invoiceInsteadReason, comment, vatInvoice,
      attachments: attachment, receiptList: invoice, bankTransactionDetails: business
    } = currentExpense;

    const { timeSupported, valid, unit } = currentExpenseType;

    const { baseCurrency } = expenseReport;

    const isMileageUnitExpense = mileageAllowanceExpenseV2DTO && mileageAllowanceExpenseV2DTO.carOrderMode === 9001;

    const isMileageStepExpense = mileageAllowanceExpenseV2DTO && mileageAllowanceExpenseV2DTO.carOrderMode === 9002;

    const mileageContent = mileageAllowanceExpenseV2DTO && mileageAllowanceExpenseV2DTO.mileageAllowanceOrders[0];

    const handleHeaderData = () => {  //header组件内容处理
      return {
        id,
        fullName: (owner || {}).fullName,
        invoiceOID,
        createdDate: new Date(createdDate).format(timeSupported ? 'yyyy-MM-dd hh:mm' : 'yyyy-MM-dd '),
        manualAudit,
        timeSupported,
        expenseTypeName,
        expenseTypeIconURL,
      };
    };

    const handleAmountArray = () => { // 金额组件内容处理

      const amountData = [];

      const content = {
        title: expenseTypeSubsidyType === 1 || mileageAllowanceExpenseV2DTO ? messages('expense-1.key698')/*实际总补贴*/ : '',
        value: amount,
        dataIndex: 'amount',
        body: [],
        originalAmount,
        currencyCode: invoiceCurrencyCode,
        hasEditedAmount: amount !== originalAmount || (actualCurrencyRate && actualCurrencyRate !== originalActualCurrencyRate)
      };

      const rateDeviation = (Math.abs(actualCurrencyRate - companyCurrencyRate) / companyCurrencyRate * 100 || 0).toFixed(1);

      const allowanceAmount =
        data.filter(field => {
          try {
            return field.fieldType === 'ALLOWANCE_DEDUCTION' && field.uniqueObj.deductionTotal > 0;
          }
          catch (e) {
            return false;
          }
        })
          .reduce((result, field) => {
            if (field.uniqueObj && !isNaN(field.uniqueObj.deductionTotal)) {
              return result + field.uniqueObj.deductionTotal;
            } else {
              return result;
            }
          }, 0);


      amountData.push(content);

      const amountBody = content.body;

      currencyCode !== baseCurrency &&
      amountBody.push(
        ...[
          {
            title: messages('expense-1.key306')/*实际汇率*/,
            value: Number(actualCurrencyRate)
              .toFixed(7)
          },
          {
            title: messages('expense-1.key303')/*企业汇率*/,
            value: Number(companyCurrencyRate || 0)
              .toFixed(7),
            isCompanyRate: true,
            rateDeviation,
            actualCurrencyRate,
            companyCurrencyRate
          },
          {
            title: messages('common.base.currency.amount')/*本位币金额*/,
            value: actualCurrencyRate * amount,
            currencyCode: baseCurrency,
          },
        ]
      );

      amountBody.push(
        [
          {
            title: messages('expense-1.key307')/*原币金额*/,
            value: originalApprovedNonVat !== null ? originalApprovedNonVat : originalAmount,
            currencyCode: invoiceCurrencyCode
          },
          {
            title: messages('expense-1.key309')/*原币税额*/,
            value: originalApprovedVat || 0,
            currencyCode: invoiceCurrencyCode
          }
        ]
      );

      valid &&
      amountBody.push(
        [
          {
            title: `${messages('common.price')/*单价*/}/${unitInfo[unit]}`,
            value: unitPrice
          },
          {
            title: messages('common.number')/*数量*/,
            value: number
          }
        ]
      );


      isMileageUnitExpense &&
      amountBody.push(
        ...[
          {
            title: messages('expense-1.key699')/*参考币种*/,
            value: (data.filter(item => item.messageKey === 'reference.currency') [0] || {}).value,
          },
          {
            title: messages('expense-1.key700')/*参考单价*/,
            value: (data.filter(item => item.messageKey === 'reference.price') [0] || {}).value,
            currencyCode: invoiceCurrencyCode
          },
          {
            title: messages('expense-1.key701')/*参考总价*/,
            value: (data.filter(item => item.messageKey === 'reference.amount') [0] || {}).value,
            currencyCode: invoiceCurrencyCode
          }]
      );


      (expenseTypeSubsidyType === 1 || isMileageStepExpense) &&
      amountData.push({
        title: messages('expense-1.key702')/*标准总补贴*/,
        dataIndex: 'subsidy',
        value: expenseTypeSubsidyType === 1 ? subsidyAmount : mileageAllowanceExpenseV2DTO.amount,
        currencyCode: invoiceCurrencyCode,
        isShowMore: isMileageStepExpense || expenseTypeSubsidyType === 1
      });


      allowanceAmount > 0 &&
      amountData.push({
        title: messages('expense-1.key321')/*扣减总额*/,
        dataIndex: 'allowanceAmount',
        value: -allowanceAmount,
        currencyCode: invoiceCurrencyCode
      });
      return amountData;
    };

    const handleFields = () => {
      const invoiceInsteadText = profile['invoice.instead.comments'] ? messages('expense-1.key296')/*是否备注*/ : messages('expense-1.key297')/*是否替票*/;

      const invoiceInsteadReasonText = profile['invoice.instead.comments'] ? messages('expense-1.key298')/*备注理由*/ : messages('expense-1.key299')/*替票理由*/;

      const hasInvoiceInstead = options['invoiceConfigOpt']['enableInstead'] && withReceipt;

      const baseMessages = [
        {
          isNotField: true,
          showValue: new Date(createdDate).format(timeSupported ? 'yyyy-MM-dd hh:mm' : 'yyyy-MM-dd '),
          name: messages('common.happened.date')/*发生日期*/,
          value: new Date(createdDate).format(timeSupported ? 'yyyy-MM-dd hh:mm' : 'yyyy-MM-dd '),
          key: 'date',
          showOnList: true,
          dataIndex:'createdDate'
        },
        {
          isNotField: true,
          showValue: vatInvoice ? messages('common.yes')/*是*/ : messages('common.no')/*否*/,
          name: messages('expense-1.key312')/*能否抵扣*/,
          value: vatInvoice ? messages('common.yes')/*是*/ : messages('common.no')/*否*/,
          key: 'deduction',
          showOnList: true,
          dataIndex:'vatInvoice'
        },
        {
          isNotField: true,
          name: messages('expense-1.key249')/*费用归属人*/,
          value: `${owner.fullName} ${owner.employeeId || owner.employeeID || ''}`,
          showValue: `${owner.fullName} ${owner.employeeId || owner.employeeID || ''}`,
          key: 'owner',
          showOnList: true,
          dataIndex:'owner'
        }
      ];

      hasInvoiceInstead && baseMessages.push(
        {
          isNotField: true,
          showValue: invoiceInstead ? messages('common.yes')/*是*/ : messages('common.no')/*否*/,
          name: invoiceInsteadText,
          value: invoiceInstead ? messages('common.yes')/*是*/ : messages('common.no')/*否*/,
          key: 'invoiceInstead',
          showOnList: true,
          dataIndex:'invoiceInstead'
        }
      );

      invoiceInstead && baseMessages.push(
        {
          isNotField: true,
          showValue: invoiceInsteadReason,
          name: invoiceInsteadReasonText,
          value: invoiceInsteadReason,
          key: 'invoiceInsteadReason',
          showOnList: true,
          dataIndex:'invoiceInsteadReason'
        }
      );

      withReceipt && (options['receiptSourceOpt']['handInvoice'] || showOCRFlag) && baseMessages.push({
          isField: false,
          isNotField: true,
          showValue: messages(receiptList.length < 1 ? 'common.no' : 'common.yes'),
          name: messages('expense-1.key300')/*录入发票*/,
          value: messages(receiptList.length < 1 ? 'common.no' : 'common.yes'),
          key: 'hasInvoice',
          showOnList: true,
          dataIndex:'hasInvoice'
        }
      );

      !isMileageStepExpense && data && data
        .filter(item => !(item.fieldType === 'PROMPT_KEY' && (item.config || {}).showOnEdit) || item.messageKey !== 'reference.mileage')
        .map(item => {
          let field = { ...item };
          if (field.messageKey === 'unit.price' && mileageAllowanceExpenseV2DTO) {
            const referenceMileageFile = data.filter(field => field.messageKey === 'reference.mileage')[0] || {};
            const middleUnit = mileageContent.mileageUnit;
            const travelMileage = mileageAllowanceExpenseV2DTO.travelMileage;
            const showTravelMileage = mileageContent.trackId;
            const referenceMileageFileValue = referenceMileageFile.value;
            let referenceMileageFileText = referenceMileageFileValue ? `${referenceMileageFile.name}: ${Math.round(referenceMileageFileValue * 100) / 100} ${middleUnit}` : '';
            const travelMileageText = showTravelMileage ? `${messages('expense-1.key153')/*行驶里程*/}: ${Math.round(travelMileage * 100) / 100} ${middleUnit}` : '';
            referenceMileageFileText = [travelMileageText, referenceMileageFileText].filter(i => !!i).join(';');
            field.value = {
              value: field.showValue,
              assist: referenceMileageFileText
            };
          }

          let formItemVisible = true;
          if (field.messageKey === 'company.payment.type') { //fix bug 28777
            data.map(fieldItem => {
              if (fieldItem.fieldType === 'COMPANY_PAID') {
                formItemVisible = fieldItem.value === '1002';
              }
            });
          }
          formItemVisible && baseMessages.push(field);
          if (field.messageKey === 'depart.place.original' && mileageAllowanceExpenseV2DTO) {
            baseMessages.push({
              isNotField: true,
              name: messages('expense-1.key149')/*途径信息*/,
              value: mileageContent.viaPoints,
              key: 'mileage',
              showOnList: true,
              speKey: 'viaPoints',
              dataIndex:'viaPoints'
            });
          }
        });


      if (isMileageUnitExpense) {
        baseMessages.push({
          isNotField: true,
          name: messages('expense-1.key314')/*行程图*/,
          value: mileageContent,
          key: 'mileage',
          showOnList: true,
          speKey: 'wayPointMap',
          dataIndex:'wayPointMap'
        });
      }

      baseMessages.push(
        {
          isNotField: true,
          showValue: comment,
          name: messages('common.accountIncident')/*事由说明*/,
          value: comment,
          key: 'remark',
          showOnList: true,
          dataIndex:'comment'
        }
      );

      if (isMileageStepExpense) {
        baseMessages.push({
          isNotField: true,
          name: messages('expense-1.key142')/*累计里程*/,
          value: {
            value: `${mileageAllowanceExpenseV2DTO.mileage.toFixed(2)} ${mileageContent.mileageUnit}`,
            assist: `${messages('expense-1.key143')/*参考里程*/}：${mileageAllowanceExpenseV2DTO.referenceMileage.toFixed(2)} ${mileageContent.mileageUnit}`
          },
          key: 'mileage',
          showOnList: true,
          speKey: 'totalMileage',
          dataIndex:'mileageUnit'
        });
      }

      return baseMessages.filter(item => {
        let messageKeys = [];
        if (mileageAllowanceExpenseV2DTO) {
          isMileageUnitExpense
            ? messageKeys = ['reference.currency', 'reference.price', 'reference.amount']
            : messageKeys = ['arrive.time', 'depart.time', 'depart.place', 'destination', 'destination.original', 'depart.place.original'];
        }
        return !['ALLOWANCE_DEDUCTION', 'PROMPT_KEY'].includes(item.fieldType) && !messageKeys.includes(item.messageKey) && item.showOnList;
      });
    };

    const handleMergeAdjuncts = () => {
      let mergeAdjuncts = [],
        adjuncts = { invoice, attachment, business },
        adjuncts_map = {
          invoice: messages('expense-1.key684')/*发票*/,
          attachment: messages('common.attachments')/*附件*/,
          business: messages('expense-1.key313')/*消费账单*/
        };

      Object.keys(adjuncts)
        .forEach(item => {
          if (adjuncts[item] && adjuncts[item][0]) {
            mergeAdjuncts.push({
              name: adjuncts_map[item],
              type: item,
              body: [...adjuncts[item]],
              length: adjuncts[item].length
            });
          }
        });
      return mergeAdjuncts;
    };

    return {
      headerData: handleHeaderData(),
      amountData: handleAmountArray(),
      fieldsData: handleFields(),
      mergeAdjuncts: handleMergeAdjuncts()
    };
  }
};
